package com.smartao.core.orm.mybatis;

import java.sql.PreparedStatement;
import java.util.Properties;

import org.apache.ibatis.executor.parameter.DefaultParameterHandler;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;

@Intercepts({@Signature(type=ParameterHandler.class,method="setParameters",args={PreparedStatement.class})})
public class PaginationParameterHandlerInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		
		DefaultParameterHandler parameterHandler = (DefaultParameterHandler)invocation.getTarget();
		MetaObject metaParameterHandler = MetaObject.forObject(parameterHandler);
		BoundSql boundSql = (BoundSql)metaParameterHandler.getValue("boundSql");
		
		PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
		
		if(boundSql.hasAdditionalParameter("paramNo")){
			int paramNo = (Integer) boundSql.getAdditionalParameter("paramNo");
			int newParams = (Integer) boundSql.getAdditionalParameter("newParams");
			int offset = (Integer) boundSql.getAdditionalParameter("offset");
			int limit = (Integer) boundSql.getAdditionalParameter("limit");
			
			if(newParams==1){
				ps.setInt(paramNo+1, limit);
			}
			if(newParams==2){
				ps.setInt(paramNo+1, limit);
				ps.setInt(paramNo+2, offset);
			}
		}
		
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}
